package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.common.ResultCode;
import com.example.smartagrisys.entity.User;
import com.example.smartagrisys.exception.BusinessException;
import com.example.smartagrisys.mapper.UserMapper;
import com.example.smartagrisys.service.UserService;
import com.example.smartagrisys.util.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User register(User user) {
        // 检查用户名是否已存在
        User existingUser = findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "用户名已存在");
        }

        // 密码加密
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        
        // 设置默认昵称（如果为空）
        if (user.getNickname() == null || user.getNickname().isEmpty()) {
            user.setNickname(user.getUsername());
        }
        
        // 设置默认状态
        user.setStatus(1);
        
        // 保存用户信息
        save(user);
        
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = findByUsername(username);
        if (user == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "用户不存在");
        }
        
        // 验证密码
        if (!MD5Util.verify(password, user.getPassword())) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "账号已被禁用");
        }
        
        return user;
    }

    @Override
    public User findByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return getOne(wrapper);
    }

    @Override
    public boolean verifyPassword(Long userId, String password) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        
        return MD5Util.verify(password, user.getPassword());
    }
    
    @Override
    public boolean changePassword(Long userId, String newPassword) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        
        // 密码加密
        user.setPassword(MD5Util.encrypt(newPassword));
        
        return updateById(user);
    }

    @Override
    public Double getUserAverageRating(Long userId) {
        // TODO: 从评价表中查询用户平均评分
        // 由于目前可能没有评价功能，暂时返回默认值5.0
        return 5.0;
    }
} 